package com.openspring.platform.service.impl;

import java.util.List;

import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.openspring.framework.service.AbstractGenericService;
import com.openspring.platform.dao.DictDAO;
import com.openspring.platform.dao.DictionaryDAO;
import com.openspring.platform.model.Dict;
import com.openspring.platform.model.Dictionary;
import com.openspring.platform.service.DictService;

@Service("dictService")
public class DictServiceImpl extends AbstractGenericService<Dict, Long> implements DictService {

	private DictDAO dictDAO;
	private DictionaryDAO dictionaryDAO;

	@Resource(name="dictDAO")
	public void setDictDAO(DictDAO dictDAO) {
		this.dictDAO = dictDAO;
		super.setGenericDAO(dictDAO);
	}
	
	@Resource(name="dictionaryDAO")
	public void setDictionaryDAO(DictionaryDAO dictionaryDAO) {
		this.dictionaryDAO = dictionaryDAO;
	}

	@Override
	public void create(Dict dict, List<Dictionary> dictionaries) {
		this.dictDAO.insert(dict);
		if(dictionaries != null && !dictionaries.isEmpty()) {
			for(Dictionary dictionary: dictionaries) {
				dictionary.setDictId(dict.getId());
			}
			this.dictionaryDAO.batchInsert(dictionaries.toArray(new Dictionary[]{}));
		}
	}

	@Override
	public void modify(Dict dict, Long[] dels, List<Dictionary> upds,
			List<Dictionary> ists) {
		this.dictDAO.update(dict);
		//以先删后改再添加的原则修改字典项
		if(dels != null && dels.length > 0) {
			this.dictionaryDAO.batchDelete(dels);
		}
		if(upds != null && !upds.isEmpty()) {
			this.dictionaryDAO.batchUpdate(upds.toArray(new Dictionary[]{}));
		}
		if(ists != null && !ists.isEmpty()) {
			for(Dictionary dictionary: ists) {
				dictionary.setDictId(dict.getId());
			}
			this.dictionaryDAO.batchInsert(ists.toArray(new Dictionary[]{}));
		}
	}
	
	@Override
	public void remove(Long id) {
		//删除字典类别前先删除该类别下的字典项
		this.dictionaryDAO.deleteByDictId(id);
		this.dictDAO.delete(id);
	}

	@Override
	public void remove(Long[] ids) {
		//删除字典类别前先删除该类别下的字典项
		this.dictionaryDAO.batchDeleteByDictId(ids);
		this.dictDAO.batchDelete(ids);
	}
}
